package com.mayuanfei.payment;

import com.mayuanfei.annotation.PayAnnotation;
import com.mayuanfei.enums.PayTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * TODO 类描述
 *
 * @author 老马
 * @date 2025-04-03 14:17
 */
@Component
@AllArgsConstructor
public class PaymentManager {

    private final Map<PayTypeEnum, Payment> paymentStrategyMap = new HashMap<>();

    @Autowired
    public PaymentManager(List<Payment> payments) {
        for (Payment payment : payments) {
            PayAnnotation annotation = payment.getClass().getAnnotation(PayAnnotation.class);
            if (annotation != null) {
                paymentStrategyMap.put(annotation.value(), payment);
            }
        }
    }

    /**
     * 根据支付类型获取支付实现类
     *
     * @param code 支付类型编码
     * @return 支付实现类
     */
    public Payment getPayerByCode(Integer code) {
        PayTypeEnum payTypeEnum = PayTypeEnum.getPayTypeEnum(code);
        return Optional.ofNullable(paymentStrategyMap.get(payTypeEnum))
                .orElseThrow(() -> new RuntimeException("未找到对应的支付类型"));
    }

    /**
     * 根据支付类型编码获取支付实现类
     *
     * @param content 支付上下文
     * @param payTypeEnum 支付类型枚举
     * @return 支付结果
     */
    public String pay(String content, PayTypeEnum payTypeEnum) {
        Payment payment = paymentStrategyMap.get(payTypeEnum);
        return payment != null ? payment.pay(content) : "未找到对应的支付类型";
    }
}